package api

import (
	"go-gw-scaffold/api/loadbanlance"
	"go-gw-scaffold/dto"
	"go-gw-scaffold/util"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

func NewLoadbanlanceReverseProxy(
	options *dto.ReverseOptions,
	manager *loadbanlance.LoadbanlanceManager,
	responseHandle func(map[string]interface{}),
) *httputil.ReverseProxy {
	instance := manager.Get(options.BanlanceType)
	for _, remote := range options.Remotes {
		instance.Add(remote)
	}
	remote, Error := instance.Get()
	if Error != nil {
		log.Fatal("loadbanlance error")
		return nil
	}
	proxyURL, _ := url.Parse(remote)
	reverseProxy := httputil.NewSingleHostReverseProxy(proxyURL)
	reverseProxy.ModifyResponse = func(r *http.Response) error {
		if r.StatusCode == 200 {
			responseData := map[string]interface{}{}
			error := util.ParseResponse(r, &responseData)
			if error != nil {
				return error
			}
			responseHandle(responseData)
			return nil
		}
		return nil
	}
	reverseProxy.ErrorHandler = func(resp http.ResponseWriter, req *http.Request, err error) {
		panic(err.Error())
	}
	originalDirector := reverseProxy.Director
	reverseProxy.Director = func(req *http.Request) {
		originalDirector(req)
		for key, header := range options.Headers {
			req.Header.Set(key, header)
		}
	}
	return reverseProxy
}
